package com.demo.supplier.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.demo.supplier.common.Pages;
import com.demo.supplier.common.R;
import com.demo.supplier.constant.ApiConstants;
import com.demo.supplier.dto.UserDto;
import com.demo.supplier.service.SysUserService;
import com.demo.supplier.vo.UserDetailVo;
import com.demo.supplier.vo.UserVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.groups.Default;

/**
 * 用户管理控制器
 * 
 * @author demo
 */
@Slf4j
@RestController
@RequestMapping("${api.prefix}" + ApiConstants.USERS)
@Api(tags = "用户管理")
public class UserController {

    @Autowired
    private SysUserService sysUserService;

    @GetMapping
    @ApiOperation("用户分页查询")
    public R<Pages<UserVo>> pageUsers(
            @ApiParam("当前页码") @RequestParam(defaultValue = "1") int current,
            @ApiParam("每页大小") @RequestParam(defaultValue = "10") int size,
            @ApiParam("搜索关键词") @RequestParam(required = false) String keyword) {
        
        Page<UserVo> page = sysUserService.pageUsers(current, size, keyword);
        Pages<UserVo> pages = Pages.of(page);
        return R.success(pages);
    }

    @GetMapping("/{id}")
    @ApiOperation("获取用户详情（包含头像信息）")
    public R<UserDetailVo> getUserById(@ApiParam("用户ID") @PathVariable Long id) {
        UserDetailVo detailVo = sysUserService.getUserWithAvatar(id);
        return R.success(detailVo);
    }

    @PostMapping
    @ApiOperation("创建用户")
    public R<String> createUser(@Validated({UserDto.Create.class, Default.class}) @RequestBody UserDto userDto) {
        sysUserService.createUser(userDto);
        return R.success("用户创建成功");
    }

    @PutMapping("/{id}")
    @ApiOperation("更新用户")
    public R<String> updateUser(
            @ApiParam("用户ID") @PathVariable Long id,
            @Validated({UserDto.Update.class, Default.class}) @RequestBody UserDto userDto) {
        userDto.setId(id);
        sysUserService.updateUser(userDto);
        return R.success("用户更新成功");
    }

    @DeleteMapping("/{id}")
    @ApiOperation("删除用户")
    public R<String> deleteUser(@ApiParam("用户ID") @PathVariable Long id) {
        sysUserService.deleteUser(id);
        return R.success("用户删除成功");
    }
}